const User = require("../models/userSchema");
const { getRecorders } = require("../utils/dbHelper");
const { getPager } = require("../utils/pageUtil");
const { debug } = require("../utils/log4jsHelper");
/**
 * 创建user
 */
const save = async function (users) {
  // 保存对象的两种方式:
  // 1. save
  // const doc = new User({ name: "O.O" });
  // await doc.save();
  // 2. create
  // const docs = await User.create([{ name: "O.O" }, { name: "K.O" }]);
  // 区别:create可以保存数组,更常用
  const docs = await User.create(users);
  return docs;
};

/**
 * 查询用户
 * @returns 用户列表
 */
const list = async function (pageNum, pageSize, conditions, filterField) {
  console.log("list ====> 查询所有用户");
  try {
    const records = await getRecorders(
      pageNum,
      pageSize,
      User,
      conditions,
      filterField
    );
    debug(`查询数据库,结果为:users=${JSON.stringify(records)}`);
    return records;
  } catch (error) {
    throw error;
  }
};

const updateUserState = async (ids) => {
  const res = await User.updateMany({ _id: { $in: ids } }, { userState: 2 });

  res.matchedCount; // Number of documents matched
  res.modifiedCount; // Number of documents modified
  res.acknowledged; // Boolean indicating everything went smoothly.
  res.upsertedId; // null or an id containing a document that had to be upserted.
  res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
  debug(`Number of documents matched: ${res.matchedCount}`);
  debug(`Number of documents modified: ${res.modifiedCount}`);
  debug(`Boolean indicating everything went smoothly: ${res.acknowledged}`);
  debug(
    `null or an id containing a document that had to be upserted: ${res.upsertedId}`
  );
  debug(
    `Number indicating how many documents had to be upserted. Will either be 0 or 1: ${res.upsertedCount}`
  );
  return res;
};

/**
 * 真正删除数据
 * @param {Array[ObjectId]} ids 需要被删除的id列表
 * @returns 结果
 */
const remove = async (ids) => {
  const res = await User.deleteMany({ _id: { $in: ids } });

  return res;
}

module.exports = {
  save,
  list,
  remove,
};
